// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Card, DatePicker, Form, Input, Select, message } from 'antd';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 路由和状态管理
import { useParams } from '@umijs/max';

// 6. 工具库
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserRoleAssignment, RoleExtension, User } from '@/services/generated';

const { TextArea } = Input;

const UserRoleForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [roles, setRoles] = useState<RoleExtension[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const isEdit = !!id;

  useEffect(() => {
    loadRoles();
    loadUsers();
    if (isEdit && id) {
      const fetchData = async () => {
        try {
          await autoLoginInDev();
          const response = await apiClients.permissions.permissionsUserRolesRetrieve({ id: parseInt(id) });
          const data = response.data;
          form.setFieldsValue({
            ...data,
            expires_at: data?.expires_at ? dayjs(String(data.expires_at)) : undefined,
          });
        } catch (error) {
          message.error('获取数据失败');
        }
      };
      fetchData();
    }
  }, [id, isEdit, form]);

  const loadRoles = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsRolesList({
        pageSize: 100,
        status: 'active',
      });
      setRoles(response.data?.items || []);
    } catch (error) {
      console.error('加载角色列表失败:', error);
    }
  };

  const loadUsers = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.users.usersList({
        pageSize: 100,
        isActive: true,
      });
      setUsers(response.data?.items || []);
    } catch (error) {
      console.error('加载用户列表失败:', error);
    }
  };

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      // 构造请求数据
      const requestData = {
        user: values.user,
        role: values.role,
        expires_at: values.expires_at ? values.expires_at.toISOString() : undefined,
        reason: values.reason,
        status: values.status || 'active',
      };

      if (isEdit) {
        await apiClients.permissions.permissionsUserRolesUpdate({ 
          id: parseInt(id!), 
          userRoleAssignmentRequest: requestData as any
        });
        message.success('更新成功');
      } else {
        await apiClients.permissions.permissionsUserRolesCreate({ 
          userRoleAssignmentRequest: requestData as any
        });
        message.success('创建成功');
      }

      window.location.href = '/permissions/user-roles';
    } catch (error) {
      message.error(isEdit ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer title={isEdit ? '编辑用户角色分配' : '新建用户角色分配'}>
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            status: 'active',
          }}
        >
          <Form.Item
            label="选择用户"
            name="user"
            rules={[{ required: true, message: '请选择用户' }]}
          >
            <Select
              placeholder="请选择用户"
              showSearch
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={users.map(user => ({
                label: `${user.username} (${user.email})`,
                value: user.id,
              }))}
            />
          </Form.Item>

          <Form.Item
            label="选择角色"
            name="role"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              placeholder="请选择角色"
              options={roles.map(role => ({
                label: role.group?.name,
                value: role.id,
              }))}
            />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select
              options={[
                { label: '激活', value: 'active' },
                { label: '禁用', value: 'inactive' },
                { label: '过期', value: 'expired' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="过期时间"
            name="expires_at"
          >
            <DatePicker
              showTime
              placeholder="选择过期时间（不选择则永不过期）"
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            label="分配原因"
            name="reason"
            rules={[
              { max: 500, message: '分配原因不能超过500个字符' },
            ]}
          >
            <TextArea
              rows={3}
              placeholder="请输入分配原因"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              {isEdit ? '更新' : '创建'}
            </Button>
            <Button style={{ marginLeft: 8 }} href="/permissions/user-roles">
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default UserRoleForm;
